// Timer realization
// (c) jimon game studio

#include "CTimer.h"

namespace je
{
	namespace core
	{
		IMPLEMENT_SINGLETON(Timer,JE_ENGINE_FUNCTION_CALL)

		//! Construct
		CTimer::CTimer()
			:Correction(0)
		{
			SetTimer(this);

			#ifdef JE_WIN
			FirstRun = true;
			Frequency = 0;
			Freq = 0;
			#endif

			#ifdef JE_LINUX
			FirstRun = true;
			#endif
		}

		//! Destruct
		CTimer::~CTimer()
		{
			SetTimer(NULL);
		}

		//! Get current programm time
		f64 CTimer::GetTime()
		{
			f64 WorkTime = 0;

			#ifdef JE_WIN
			if(FirstRun)
			{
				f64 DefFreq = 10000000;

				Frequency=DefFreq;
				Freq = DefFreq;

				QueryPerformanceFrequency (&basefrequency);
				Frequency = basefrequency.QuadPart / Frequency;

				QueryPerformanceCounter(&perfTime);
				Started=perfTime;

				FirstRun = 0;
			}

			QueryPerformanceCounter(&perfTime);
			LastValue = (perfTime.QuadPart - Started.QuadPart) / Frequency;

			WorkTime = (LastValue / Freq)*1000.0;
			#endif

			#ifdef JE_LINUX
			if(FirstRun)
			{
				gettimeofday(&TimeStart,&TimeZone);
				FirstRun = 0;
			}
			gettimeofday(&TimeEnd,&TimeZone);

			f64 TimeStartNum, TimeEndNum;
			TimeStartNum =  (f64)TimeStart.tv_sec + (f64)TimeStart.tv_usec/(1000*1000);
			TimeEndNum =  (f64)TimeEnd.tv_sec + (f64)TimeEnd.tv_usec/(1000*1000);
			WorkTime = (TimeEndNum-TimeStartNum)*1000.0;
			#endif

			return WorkTime + Correction;
		}

		//! If we need to correct return time, +1 add 1 millisec to return time, -1 sub one millisec
		void CTimer::SetTimeCorrection(f64 Corr)
		{
			Correction = Corr;
		}
	}
}
